import type { RouteKey, RoutePath } from '@elegant-router/types';
import { useSvgIcon } from '@/hooks/common/icon';

/** 将后端菜单数据转换为前端菜单格式 */
export function transformBackendMenuToFrontendMenu(backendMenus: Api.SystemManage.Menu[]): App.Global.Menu[] {
  const { SvgIconVNode } = useSvgIcon();

  return backendMenus
    .filter(menu => menu.status === '1' && !menu.hideInMenu) // 只显示启用的菜单
    .map(menu => {
      // 暂时直接使用menuName，不使用i18nKey
      const label = menu.menuName;

      // 构建 meta 字段，保留 icon/localIcon 字符串，title, i18nKey
      const meta = {
        icon: menu.iconType === '1' ? menu.icon : undefined,
        localIcon: menu.iconType === '2' ? menu.icon : undefined,
        title: menu.menuName,
        i18nKey: menu.i18nKey
      };

      const frontendMenu = {
        key: menu.routeName || `menu_${menu.id}`,
        label,
        i18nKey: menu.i18nKey,
        routeKey: menu.routeName as RouteKey,
        routePath: menu.routePath as RoutePath,
        title: label,
        // 用类型断言绕过 meta 字段类型检查
        meta
      } as App.Global.Menu & { meta: Record<string, any> };

      // 处理图标（VNode 用于菜单渲染）
      if (meta.icon) {
        frontendMenu.icon = SvgIconVNode({ icon: meta.icon });
      } else if (meta.localIcon) {
        frontendMenu.icon = SvgIconVNode({ localIcon: meta.localIcon });
      }

      // 处理子菜单
      if (menu.children && menu.children.length > 0) {
        frontendMenu.children = transformBackendMenuToFrontendMenu(menu.children);
      }

      return frontendMenu;
    })
    .sort((a, b) => {
      // 按orderNum排序，需要从原始数据中获取orderNum
      const aMenu = backendMenus.find(m => m.routeName === a.routeKey);
      const bMenu = backendMenus.find(m => m.routeName === b.routeKey);
      const aOrder = aMenu?.orderNum || 0;
      const bOrder = bMenu?.orderNum || 0;
      return aOrder - bOrder;
    });
}

/** 检查菜单是否有权限访问 */
export function checkMenuPermission(menu: Api.SystemManage.Menu, userRoles: string[]): boolean {
  // 如果没有设置角色限制，则所有人都可以访问
  if (!menu.roles || menu.roles.length === 0) {
    return true;
  }

  // 检查用户是否有菜单所需的角色
  return menu.roles.some(role => userRoles.includes(role));
}

/** 过滤有权限的菜单 */
export function filterMenusByPermission(menus: Api.SystemManage.Menu[], userRoles: string[]): Api.SystemManage.Menu[] {
  return menus
    .filter(menu => checkMenuPermission(menu, userRoles))
    .map(menu => ({
      ...menu,
      children: menu.children ? filterMenusByPermission(menu.children, userRoles) : undefined
    }))
    .filter(menu => {
      // 如果是目录类型，至少要有子菜单才显示
      if (menu.menuType === '1') {
        return menu.children && menu.children.length > 0;
      }
      return true;
    });
}

/** 根据用户角色菜单权限过滤菜单 递归检查所有层级，如果某个菜单或其任何子菜单在权限列表中，则保留该菜单 */
export function filterMenusByUserRoleMenus(
  menus: Api.SystemManage.Menu[],
  userRoleMenuIds: number[]
): Api.SystemManage.Menu[] {
  const filteredMenus: Api.SystemManage.Menu[] = [];

  for (const menu of menus) {
    // 递归处理子菜单
    const filteredChildren = menu.children ? filterMenusByUserRoleMenus(menu.children, userRoleMenuIds) : undefined;

    // 检查当前菜单是否在权限列表中
    const hasCurrentMenuPermission = userRoleMenuIds.includes(menu.id);

    // 检查是否有子菜单权限
    const hasChildrenPermission = filteredChildren && filteredChildren.length > 0;

    // 如果当前菜单有权限或有子菜单权限，则保留该菜单
    if (hasCurrentMenuPermission || hasChildrenPermission) {
      const filteredMenu: Api.SystemManage.Menu = {
        ...menu,
        children: filteredChildren
      };
      filteredMenus.push(filteredMenu);
    }
  }

  // 过滤掉目录类型但没有子菜单的菜单
  return filteredMenus.filter(menu => {
    if (menu.menuType === '1') {
      return menu.children && menu.children.length > 0;
    }
    return true;
  });
}
